var app = require('express')()
var server = require('http').createServer(app)
var io = require('socket.io').listen(server);


var port = process.env.PORT || 3000
var mongoose = require('mongoose')
var User = require('./api/models/userModel')
var bodyParser = require('body-parser')

mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/expressapp');


// 应用层中间件
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// 应用层路由
var userRoutes = require('./api/routes/userRoute')
userRoutes(app)

var postRoutes = require('./api/routes/postRoute')
postRoutes(app)


/*app.use("/api", function(req, res, next) {
    res.send("Hellow World")
})
*/

var users = [];
io.sockets.on('connection', function(socket) {
    socket.emit('a', { hello: 'world' });


    socket.on('online', function(data) {
        var username = data.username;
        var avatar = data.avatar;
        socket.name = username;
        if (users.indexOf(username) == -1) {
            users.push(username)
        }
        io.sockets.emit('online', { users: users, user: username, avatar: avatar });
    });

    socket.on('message', function(data) {
        var say = data.say;
        var avatar = data.avatar;
        socket.name = say;
        io.sockets.emit('message', { message: say, avatar: avatar });
    });
});

server.listen(port);

console.log(`You server now listening on port: ${port} `);